<template>
  <el-header
    class="app-header"
    :style="{ background: 'linear-gradient(90deg, #acb3d8 0%, #9176db 100%)' }"
  >
    <div class="header-content">
      <!-- Logo 区域 -->
      <div class="logo-container">
        <img src="../assets/logo.png" alt="音了个音" class="logo" />
      </div>
      <!-- 导航链接区域 -->
      <div class="nav-links">
        <router-link to="/" class="nav-link" exact-active-class="active"
          >首页</router-link
        >
        <router-link to="/playlist" class="nav-link" active-class="active"
          >歌单</router-link
        >
        <router-link to="/singer" class="nav-link" active-class="active"
          >歌手</router-link
        >
        <router-link to="/my-music" class="nav-link" active-class="active"
          >我的音乐</router-link
        >
        <router-link to="/recommend" class="nav-link" active-class="active"
          >排行榜</router-link
        >
      </div>
      <!-- 搜索框 -->
      <div class="search-container">
        <el-input
          class="search-input"
          v-model="searchText"
          placeholder="搜索歌曲、歌手、专辑"
          prefix-icon="el-icon-search"
          @keyup.enter.native="handleSearch"
          clearable
        >
          <template #append>
            <el-button @click="handleSearch">搜索</el-button>
          </template>
        </el-input>
      </div>
      <!-- 用户操作区域 -->
      <div class="user-actions">
        <!-- 登录按钮 -->
        <el-button
          v-if="!isLoggedIn"
          type="primary"
          @click="showLoginModal = true"
          >登录</el-button
        >
        <!-- 已登录状态显示自定义菜单 -->
        <div v-else class="custom-dropdown">
          <div class="user-profile" @click="toggleMenu">
            <img
              :src="
                userInfo.avatarUrl || 'https://picsum.photos/50/50?random=1'
              "
              alt="用户头像"
              class="user-avatar"
            />
            <i class="el-icon-caret-bottom"></i>
          </div>
          <!-- 自定义菜单内容 -->
          <transition name="el-zoom-in-top">
            <div v-show="showMenu" class="menu-items">
              <div class="menu-item" @click="navigateTo('profile')">
                <i class="el-icon-user"></i>
                <span>个人信息</span>
              </div>
              <div class="menu-item" @click="navigateTo('messages')">
                <i class="el-icon-chat-dot-round"></i>
                <span>我的消息</span>
              </div>
              <div class="menu-item" @click="navigateTo('subscription')">
                <i class="el-icon-star"></i>
                <span>VIP订阅与续费</span>
              </div>
              <div class="menu-divider"></div>
              <div class="menu-item" @click="logout">
                <i class="el-icon-switch-button"></i>
                <span>退出登录</span>
              </div>
            </div>
          </transition>
        </div>
        <!-- 设置图标 -->
        <el-tooltip content="设置" placement="bottom">
          <i
            class="el-icon-setting user-icon"
            @click="navigateTo('settings')"
          ></i>
        </el-tooltip>
      </div>
    </div>
    <!-- 登录/注册对话框 -->
    <el-dialog
      v-model="showLoginModal"
      title="欢迎回来"
      width="400px"
      custom-class="login-dialog"
      :close-on-click-modal="false"
      @close="handleClose"
    >
      <template #default>
        <el-tabs
          v-model="activeTab"
          @tab-click="handleTabClick"
          class="custom-split-tabs"
        >
          <el-tab-pane label="登录" name="login"></el-tab-pane>
          <el-tab-pane label="注册" name="register"></el-tab-pane>
        </el-tabs>
        <div v-show="activeTab === 'login'">
          <el-form :model="loginForm" label-width="70px">
            <el-form-item label="邮箱">
              <el-input v-model="loginForm.email" type="email"></el-input>
            </el-form-item>
            <el-form-item label="密码">
              <el-input v-model="loginForm.password" type="password"></el-input>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
            </el-form-item>
          </el-form>
        </div>
        <div v-show="activeTab === 'register'">
          <el-form :model="registerForm" label-width="70px">
            <el-form-item label="邮箱">
              <el-input v-model="registerForm.email" type="email"></el-input>
            </el-form-item>
            <el-form-item label="用户名">
              <el-input v-model="registerForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码">
              <el-input
                v-model="registerForm.password"
                type="password"
              ></el-input>
            </el-form-item>
            <el-form-item label="确认密码">
              <el-input
                v-model="registerForm.confirmPassword"
                type="password"
              ></el-input>
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="registerForm.phone"></el-input>
            </el-form-item>
            <el-form-item label="昵称">
              <el-input v-model="registerForm.nickname"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="social-login">
          <p>使用其他方式登录</p>
          <div class="social-icons">
            <el-button
              icon="el-icon-wechat"
              type="success"
              circle
              size="small"
            ></el-button>
            <el-button
              icon="el-icon-qq"
              type="info"
              circle
              size="small"
            ></el-button>
            <el-button
              icon="el-icon-weibo"
              type="danger"
              circle
              size="small"
            ></el-button>
          </div>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showLoginModal = false">取消</el-button>
          <el-button
            type="primary"
            @click="activeTab === 'login' ? login() : register()"
          >
            {{ activeTab === "login" ? "登录" : "注册" }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-header>
</template>

<script>
import { useUserStore } from "@/stores/user";
import api from "../services/api";

export default {
  name: "Header",
  data() {
    return {
      showLoginModal: false,
      showMenu: false,
      activeTab: "login",
      activeMenu: "home",
      searchText: "",
      loginForm: {
        email: "",
        password: "",
        remember: false,
      },
      registerForm: {
        email: "",
        username: "",
        password: "",
        confirmPassword: "",
        phone: "",
        nickname: "",
        gender: 0,
        birthday: null,
      },
    };
  },
  computed: {
    userStore() {
      return useUserStore();
    },
    isLoggedIn() {
      return this.userStore.isLoggedIn;
    },
    userInfo() {
      return this.userStore.userInfo;
    },
  },
  methods: {
    handleSelect(key) {
      this.activeMenu = key;
    },
    async login() {
      try {
        const response = await api.userApi.login({
          usernameOrEmail: this.loginForm.email,
          password: this.loginForm.password,
        });
        console.log("登录响应:", response);
        if (response.code === 200) {
          // 确保登录数据包含用户信息
          const loginData = {
            token: response.data.token,
            userInfo: response.data.userInfo || {
              userId: response.data.userId,
            },
          };
          console.log("准备存储的登录数据:", loginData);

          this.userStore.login(loginData); // 存储token和登录状态
          this.showLoginModal = false;
          this.$message.success("登录成功！");
        } else {
          this.$message.error(response.msg || "登录失败，请检查用户名和密码");
        }
      } catch (error) {
        console.error("登录失败:", error);
        this.$message.error("登录失败，请检查用户名和密码");
      }
    },
    async register() {
      try {
        const response = await api.userApi.register({
          username: this.registerForm.username,
          password: this.registerForm.password,
          email: this.registerForm.email,
          phone: this.registerForm.phone,
          nickname: this.registerForm.nickname,
          gender: this.registerForm.gender,
          birthday: this.registerForm.birthday,
          hobby: this.registerForm.hobby || "未设置",
          introduction: this.registerForm.introduction || "暂无介绍",
          avatarUrl:
            this.registerForm.avatarUrl || "/images/avatars/default.jpg",
        });
        // 注册成功后可自动登录
        // if (response.code === 200) {
        //   this.userStore.login(response.data);
        //   await this.userStore.fetchUserDetail();
        //   this.showLoginModal = false;
        //   this.$message.success("注册成功！已自动登录");
        // }
      } catch (error) {
        console.error("注册失败:", error);
        this.$message.error("注册失败，请检查输入信息");
      }
    },
    handleTabClick(tab) {
      this.activeTab = tab.name;
    },
    handleClose() {
      this.loginForm = {
        email: "",
        password: "",
        remember: false,
      };
      this.registerForm = {
        email: "",
        username: "",
        password: "",
        confirmPassword: "",
        phone: "",
        nickname: "",
        gender: 0,
        birthday: null,
      };
    },
    toggleMenu() {
      this.showMenu = !this.showMenu;
    },
    logout() {
      this.userStore.logout();
      this.showMenu = false;
      this.$message.info("已退出登录");
    },
    navigateTo(route) {
      this.showMenu = false;
      switch (route) {
        case "profile":
          // 检查登录状态和用户ID
          if (this.userStore.isLoggedIn) {
            const userId = this.userStore.getUserId();
            console.log("当前用户ID:", userId);
            if (userId) {
              // 有用户ID，直接跳转，组件内会自动刷新数据
              this.$router.push(`/user/profile`);
            } else {
              // 没有用户ID，先尝试获取
              this.$message.info("正在获取用户信息...");
              this.userStore
                .fetchUserDetail()
                .then(() => {
                  this.$router.push(`/user/profile`);
                })
                .catch((error) => {
                  console.error("获取用户信息失败:", error);
                  this.$message.error("获取用户信息失败，请重新登录");
                  this.userStore.logout();
                  this.showLoginModal = true;
                });
            }
          } else {
            this.$message.warning("请先登录");
            this.showLoginModal = true;
          }
          break;
        case "messages":
          this.$router.push("/user/messages");
          break;
        case "vip":
          this.$router.push("/vip/level");
          break;
        case "subscription":
          this.$router.push("/vip/subscription");
          break;
        case "settings":
          this.$router.push("/settings");
          break;
        default:
          this.$router.push("/");
      }
    },
    handleSearch() {
      if (!this.searchText.trim()) {
        this.$message.warning("请输入搜索关键词");
        return;
      }
      this.$router.push({
        path: "/search",
        query: {
          keyword: this.searchText,
          type: "all",
        },
      });
    },
  },
  async mounted() {
    this.userStore.initUserState();
    if (this.userStore.isLoggedIn) {
      await this.userStore.fetchUserDetail();
    }
    document.addEventListener("click", (e) => {
      if (!this.$el.contains(e.target)) {
        this.showMenu = false;
      }
    });
  },
};
</script>

<style scoped>
.app-header {
  padding: 0 20px;
  color: white;
  height: 60px; /* 调整头部高度 */
  position: relative;
  display: flex;
  align-items: center;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.logo-container {
  margin-right: 20px;
  display: flex;
  align-items: center;
}

.logo {
  width: 70px; /* 调整Logo大小 */
  height: 70px;
  border-radius: 50%;
  background: #554d5b;
  padding: 10px;
  margin-top: 18px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.logo:hover {
  transform: scale(1.05);
}

.nav-links {
  display: flex;
  align-items: center;
  gap: 50px; /* 调整导航链接间距 */
  flex: 1;
  max-width: 600px;
}

.nav-link {
  color: white;
  margin-top: 15px;
  text-decoration: none;
  font-size: 18px; /* 修改导航链接字体大小和颜色 */
  transition: color 0.3s;
  white-space: nowrap;
}

.nav-link:hover,
.nav-link.active {
  color: #f0f0f0;
  font-weight: 500;
}

.search-container {
  display: flex;
  align-items: center;
  width: 350px;
  margin-right: 15px;
  margin-top: 15px;
  margin-left: -30px;
}

.search-input {
  width: 280px;
  background: #ffffff;
  border: none;
  border-radius: 12px;
  color: white;
}

.advanced-search-link {
  color: #f0f0f0;
  font-size: 12px;
  margin-left: 10px;
  cursor: pointer;
  padding: 3px 8px;
  border-radius: 10px;
  transition: background-color 0.3s;
}

.advanced-search-link:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.nav-link.active {
  color: #f0f0f0;
  font-weight: 500;
  border-bottom: 2px solid #f0f0f0; /* 添加下划线 */
  padding-bottom: 5px; /* 调整下划线与文字间距 */
}

.user-actions {
  display: flex;
  align-items: center;
  gap: 10px; /* 调整用户区域间距 */
}

.user-actions .el-button {
  padding: 6px 20px; /* 调整登录按钮大小 */
  font-size: 12px;
  margin-top: 15px;
  background-color: #d1c4e9; /* 新增淡紫色背景 */
  border-color: #d1c4e9; /* 新增淡紫色边框 */
  color: #a963d4; /* 深紫色文字 */
}

.user-actions .el-button:hover {
  background-color: #dac3f4; /* 更浅的悬停效果 */
  border-color: #e1bee7;
}

.user-profile {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.user-avatar {
  width: 36px; /* 调整头像大小 */
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid white;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
  margin-right: 5px;
  margin-top: 15px;
}

.user-icon {
  font-size: 18px; /* 调整图标大小 */
  cursor: pointer;
  padding: 5px;
  border-radius: 50%;
  transition: background-color 0.3s;
}

/* 下拉菜单样式保持不变 */
.custom-dropdown {
  position: relative;
}

.menu-items {
  position: absolute;
  right: 0;
  top: 100%;
  width: 180px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 100;
  margin-top: 5px;
}

.menu-item {
  padding: 10px 15px;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: background-color 0.3s;
  color: #606266;
}

.menu-item:hover {
  background-color: #f5f7fa;
  color: #9176db;
}

.menu-item i {
  margin-right: 10px;
  width: 16px;
  text-align: center;
  font-size: 16px;
}

.menu-item span {
  font-size: 14px;
}

.menu-divider {
  height: 1px;
  background-color: #ebeef5;
  margin: 5px 0;
}

/* 登录对话框样式保持不变 */
.login-dialog .el-dialog {
  border-radius: 12px;
  max-height: 500px;
}

.login-dialog .el-dialog__body {
  padding: 15px 20px;
}

.login-dialog .el-form-item {
  margin-bottom: 16px;
}

.login-dialog .el-form-item__label {
  font-size: 14px;
}

.login-dialog .el-input__inner {
  font-size: 14px;
}

.social-login {
  margin-top: 15px;
  text-align: center;
}

.social-login p {
  font-size: 13px;
  color: #999;
  margin-bottom: 10px;
}

.social-icons {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.custom-split-tabs > .el-tabs__header {
  margin: 0 !important;
}

.custom-split-tabs .el-tabs__nav {
  display: flex !important;
  width: 100% !important;
  border: none !important;
  justify-content: space-between !important;
}

.custom-split-tabs .el-tabs__item {
  flex: 1 !important;
  text-align: center !important;
  padding: 0 12px !important;
  height: 40px !important;
  line-height: 40px !important;
}

.custom-split-tabs .el-tabs__active-bar {
  width: 50% !important;
  height: 3px !important;
}

.custom-split-tabs
  .el-tabs__item.is-active:nth-child(1)
  ~ .el-tabs__active-bar {
  transform: translateX(0%) !important;
}

.custom-split-tabs
  .el-tabs__item.is-active:nth-child(2)
  ~ .el-tabs__active-bar {
  transform: translateX(100%) !important;
}
</style>
